<template>
	<view class="" v-if="formData.soup_status != undefined && !isAdminRole()">
		<uni-notice-bar showIcon :text="`通知：${soupStateFormat.text}, ${(soupStateFormat.value == 0 || soupStateFormat.value == 1)? '不允许再次编辑' :'原因：' + 
			formData.reject_reason+ '，修改后可再次提交'}`" :background-color="soupStateFormat.bgColor"
			:color="soupStateFormat.color"></uni-notice-bar>

	</view>

	<view class="editLayout">
		
		
		<view class="row" v-if="formData.user_id && isAdminRole()">
			<view class="head">
				<view class="title">发布者</view>
			</view>
		
			<view class="body">
				<view class="userinfo">
					<image :src="formData.avatar || '../../static/images/defAvatar.png'" mode="aspectFill"></image>
					<text class="name">{{formData.username}}</text>
				</view>
			</view>
		</view>
		
		
		
		<view class="row">
			<view class="head">
				<view class="title">鸡汤类型</view>
			</view>

			<view class="body">
				<radio-group @change="radioChange">
					<lable class="radio">
						<radio value="0" :disabled="editDisabled" color="#4F9153" :checked="formData.soup_type==0" />毒鸡汤
					</lable>
					<lable class="radio">
						<radio value="1" :disabled="editDisabled" color="#f83162" :checked="formData.soup_type==1" />心里鸡汤
					</lable>
				</radio-group>
			</view>
		</view>


		<view class="row">
			<view class="head">
				<view class="title">鸡汤内容</view>
				<text class="subTitle">
					1.一行不超过12个字，最多5行\n
					2.毒鸡汤、心灵鸡汤、有感而发均可\n
					3.提交后管理员审核，有可能会微调
				</text>
			</view>

			<view class="body">
				<textarea class="soupContent" :disabled="editDisabled" placeholder="编写你的鸡汤吧~~"
					v-model="formData.soup_content"></textarea>
			</view>
		</view>

		<view class="row">
			<view class="head">
				<view class="title">添加出处</view>
				<text class="subTitle">如果是摘抄的，建议添加出处</text>
			</view>
			<view class="body">
				<input class="fromIpt" :disabled="editDisabled" v-model="formData.from" type="text" placeholder="如:《红楼梦》">
			</view>
		</view>
		
		
		<view class="row" v-if="isAdminRole() && formData._id">
			<view class="head"><view class="title">鸡汤状态</view></view>
			<view class="body">
				<radio-group @change="statusChange">
					<lable class="radio" v-for="item in stateLists" :key="item.value">
						<view><!-- 换行 -->
							<radio :value="item.value"  color="#4F9153" :checked="formData.soup_status==item.value" />{{item.text}}
						</view>
					</lable>
				</radio-group>
			</view>
		</view>
		

		<view class="row btnGroup">
			<view class="body">
				<button type="primary" @click="onSubmit" v-if="isAdminRole()" :disabled="statusDisabled || editDisabled">发布鸡汤</button>
<!-- 				<button type="primary" @click="onSubmit" v-else :disabled="statusDisabled || editDisabled">提交审核</button> -->
				<button type="primary" @click="onSubmit" v-else>提交审核</button>
			</view>
		</view>


	</view>
</template>

<script setup>
	import {ref,computed} from 'vue';
	import {showToast,stateFormat,stateLists} from "../../utils/common.js"
	import {removeHtmlTags,isAdminRole} from "../../utils/tools.js";
	import {onLoad} from "@dcloudio/uni-app"
	import {useUserStore} from "@/stores/user.js"


	const userStore = useUserStore()
	
	// 提交表单
	const db = uniCloud.database();
	// 提交后不能再次提交，防止二次提交
	const statusDisabled = ref(false)
	// 防止审核中和审核成功再次编辑 0和1不可编辑
	//const editDisabled = computed(() => formData.value.soup_status != 2 && !isAdminRole())
	const editDisabled = false
	const formData = ref({
		_id: undefined,
		soup_type: undefined,
		soup_content: '',
		soup_status: undefined,
		from: '',
		reject_reason: undefined,
		review_uid: undefined,
		user_id: undefined,
		username: undefined,
		avatar: undefined
	})

	// 计算属性
	const soupStateFormat = computed(() => stateFormat(formData.value.soup_status))


	// 需要引入对应的uniap的包,onLoad一般是用于接受上一个页面的参数会用到他，组件还没挂载所以拿不到组件的ref信息
	onLoad((e) => {
		const {
			_id,
			user_id,
			soup_type,
			content,
			soup_status,
			from,
			reject_reason
		} = e;
		formData.value._id = _id;
		formData.value.soup_type = soup_type;
		formData.value.soup_content = content;
		formData.value.soup_status = soup_status;
		formData.value.from = from;
		formData.value.reject_reason = reject_reason;
		
		// 关联查询
		let userTemp = db.collection("uni-id-users").where({
			_id: user_id
		}).field("_id,username,avatar").get().then(res=>{
			let  {
				username,
				avatar
			} = res.result.data[0]
			formData.value.username = username
			formData.value.avatar = avatar
		})
		
		
		
		
		
		// 查询下用户头像
		// if (formData.value._id) {
		// 	db.collection('soup-chicken').doc(_id).get().then(res => {
		// 		console.log( res.result)
		// 		// fromData.value.avatar = 
		// 	})
		// }
		
		
		uni.setNavigationBarTitle({
			title: _id ? '编辑鸡汤' : '新增鸡汤'
		})
	})

	const onSubmit = async () => {
		formData.value.soup_content = removeHtmlTags(formData.value.soup_content)
		if (formData.value.soup_content.length < 1) {
			showToast('鸡汤内容不能为空', "error")
			return
		}
		try {
			uni.showLoading({
				title: '提交中。。。'
			})



			let errCode, res;
			let {
				soup_content,
				soup_type,
				from,
				soup_status
			} = formData.value;
			let db_item = {
				content: soup_content,
				soup_type: Number(soup_type),
				from,
				soup_status: isAdminRole() ? soup_status:0,
				last_modify_date: Date.now(), // 时间戳
				review_uid: undefined
			}
			// 如果有_id，则是编辑操作，否则是新增操作
			if (formData.value._id) {
				if(!isAdminRole()) formData.soup_status = 0
				if(isAdminRole()) db_item.review_uid = userStore.userInfo._id
				// 编辑操作 doc等同于 .where(_id:formData.value._id)
				res = await db.collection('soup-chicken').doc(formData.value._id).update(db_item)
			} else {
				// 新增操作
				res = await db.collection('soup-chicken').add({
					content: formData.value.soup_content,
					soup_type: formData.value.soup_type,
					from: formData.value.from,
					soup_status:isAdminRole() ? 1:0
				})
			}
			if (res.result.errCode == 0) {
				showToast('提交成功', 'success')
				statusDisabled.value = true;
				uni.$emit("addSoupSucc", "{msg:'hello word'}") // 新增成功，跳转到上一个页面，并触发一个广播发布订阅事件
				setTimeout(() => uni.navigateBack(), 1000)
			}

		} catch (err) {
			console.log(err)
			showToast(err.errMsg, 'error')
		} finally {
			uni.hideLoading()
		}

	}

	const radioChange = (e) => {
		// 按钮是字符串，数据库是int类型 必须保持类型一致，否则控制台报错
		formData.value.soup_type = Number(e.detail.value)
	}

	const statusChange = (e) => {
		// 按钮是字符串，数据库是int类型 必须保持类型一致，否则控制台报错
		formData.value.soup_status = Number(e.detail.value)
	}


	// 审核中、审核通过的不能再次编辑
</script>

<style scoped lang="scss">
	.editLayout {

		padding: 30rpx;

		.row {
			padding-bottom: 30rpx;

			.head {
				padding: 20rpx 0;
				padding-left: 20rpx;

				.title {
					font-size: 34rpx;
					padding-left: 20rpx;

					position: relative; // 相对定位
					padding-bottom: 6rpx;
					// &::before 是一个伪元素，它在.title元素之前插入内容。这个伪元素的样式如下
					position: relative;
					padding-bottom: 6rpx;

					&::before {
						content: "";
						display: block;
						width: 8rpx;
						height: 30rpx;
						background: $brand-theme-color;
						position: absolute; // 绝对定位
						left: 0;
						top: calc(50% - 15rpx);
						border-radius: 10rpx;
					}
				}

				.subTitle {
					font-size: 26rpx;
					color: $text-font-color-3;
				}

			}

			.body {
				.userinfo{
					display: flex;
					align-items: center;
					.pic{
						width: 60rpx;
						height: 60rpx;
						border-radius: 50%;
					}
					.name{
						padding-left:10rpx;
					}
				}
				.radio {
					margin-right: 35rpx;

					radio {
						transform: scale(0.7);
					}
				}

				.soupContent {
					border: 1px solid $border-color-light;
					background: #FCFCFC;
					width: 100%;
					height: 400rpx;

					padding: 20rpx;
					border-radius: 10rpx;
					font-size: 50rpx;
				}

				.fromIpt {
					border: 1px solid $border-color-light;
					background: #FCFCFC;
					height: 80rpx;
					padding: 0 20rpx;
					border-radius: 10rpx;

				}


			}
		}

		.btnGroup {
			padding-top: 60rpx;
		}


	}


	// 属性选择器 排除button
	[disabled]:not(button) {
		color: #bbb;

	}
</style>